﻿using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace StockTradTest.Data
{
    /// <summary>
    /// 指数数据库操作
    /// </summary>
    public class IndexDatabase
    {
        readonly SQLiteAsyncConnection _database;

        public IndexDatabase(string dbPath)
        {
            _database = new SQLiteAsyncConnection(dbPath);
            _database.CreateTableAsync<Index>().Wait();

        }
        public Task<Index> GetIndexAsync(int date)
        {
            return _database.Table<Index>()
                            .Where(i => i.Date == date)
                            .FirstOrDefaultAsync();
        }

        public Task<Index> GetIndexAsync(string code, int date)
        {
            Base.CurrentCode = code;
            return Base.IndexDatabase.GetIndexAsync(date);
        }
        public Task<List<Index>> GetIndexAsync(int startDate = 0, int endDate = int.MaxValue)
        {
            if (endDate == int.MaxValue & startDate == 0)
            {
                return _database.Table<Index>().
                ToListAsync();
            }
            return _database.Table<Index>().
                Where(i => i.Date > startDate & i.Date < endDate).
                ToListAsync();
        }
        //股票顺序为0-count：最旧-最新
        public async Task<int> SaveAllIndexAsync(List<Index> indexs)
        {
            if (indexs == null || indexs.Count == 0) return 0;
            //数据库中该股票信息
            List<Index> checkIndexs = GetIndexAsync().Result;
            if (checkIndexs == null || checkIndexs.Count == 0)
            {
                return await _database.InsertAllAsync(indexs);
            }
            //数据库中最新的日期股票信息
            Index upToDateIndex = checkIndexs[checkIndexs.Count - 1];
            //从最新日期开始计算
            for (int i = 0; i < indexs.Count; i++)
            {
                //从最新的开始比对
                if (indexs[i].Date == upToDateIndex.Date)
                {
                    if (indexs[i].ClosePrice == upToDateIndex.ClosePrice)
                        return await _database.InsertAllAsync(indexs.GetRange(i + 1, indexs.Count - i - 1));
                    else
                    {
                        await _database.Table<Index>().DeleteAsync();
                        return await _database.InsertAllAsync(indexs);
                    }
                }
            }
            return await _database.InsertAllAsync(indexs);
        }

        public Task<int> DeleteIndexAsync(Index index)
        {
            return _database.DeleteAsync(index);
        }
    }
}
